<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :show-close="true"
    :class="{'mobile-el-dialog-form global-mobile-dialog': showMobilePage}"
    class="medium-common-dialog-size"
  >
    <div class="task-box">
      <Title :title="!kindId?'添加任务通知':'编辑任务通知'" font-size="16px" style="margin-bottom:16px;"/>
      <el-form
        ref="configKindForm"
        :rules="rules"
        :model="queryData"
        :class="{'mobile-el-form': showMobilePage}"
        :label-position="showMobilePage?'left':'right'"
        label-width="80px"
        class="notice-form">
        <el-row type="flex" class="response-el-row">
          <el-col :span="showMobilePage ? 24 : 12" >
            <el-form-item label="通知类型" prop="module">
              <el-select
                v-select-scroll="true"
                v-model="queryData.module"
                size="small"
                multiple
                clearable
                placeholder="请选择模块"
                @change="handleModule">
                <el-option
                  v-for="item in taskModulesOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                  :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="queryData.module.includes(4)" :span="showMobilePage ? 24 : 12" >
            <el-form-item label="跟进人" prop="followUsers">
              <selectWithUserLoad
                ref="proposerRef"
                v-model="queryData.followUsers"
                :value-type="'object'"
                :hide-select-list="queryData.followUsers || []"
                :show-check-user="true"
                style="width:200px;"
                key-name="id"
                label-name="userName"
                filterable
                multiple
              />
            </el-form-item>
          </el-col>
          <el-col v-if="!queryData.module.includes(4)" :span="showMobilePage ? 24 : 12" >
            <el-form-item label="通知范围" prop="type">
              <selectWithoutHttp
                v-model="queryData.type"
                :list-data="typeOptions"
                placeholder="请选择通知类型"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="!queryData.module.includes(4)" :span="showMobilePage ? 24 : 12" >
            <el-form-item label="通知对象" prop="receive">
              <filter-cascader
                v-if="queryData.type === 0"
                v-model="queryData.receiveDept"
                :options="deptTreeList"
                :collapse-tags="true"
                placeholder="请选择部门"
              />
              <selectWithUserLoad
                v-if="queryData.type === 1"
                v-model="queryData.receiveUser"
                :default-list="queryData.receiveUser || []"
                :value-type="'object'"
                key-name="id"
                style="width:200px;"
                label-name="userName"
                placeholder="请选择人员"
                multiple
                filterable
                collapse-tags
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col v-if="!queryData.module.includes(4)" :span="showMobilePage ? 24 : 12" >
            <el-form-item label="抄送人" prop="copyReceive">
              <el-cascader
                v-select-scroll
                v-if="dialogVisible"
                ref="ding-cascader"
                v-model="queryData.copyReceive"
                :show-all-levels="false"
                :options="allDeptList"
                :props="{
                  multiple: true,
                  value: 'id',
                  label: 'value',
                  emitPath: false
                }"
                filterable
                class="ding-user-select multiply-select-scroll"
                popper-class="ding-user-select"
                size="small"
                clearable
                collapse-tags
              >
                <template slot-scope="{ data }">
                  <ToolTip :content="data.value" />
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="showMobilePage ? 24 : 12" >
            <el-form-item label="通知周期" prop="cycle">
              <selectWithoutHttp
                v-model="queryData.cycle"
                :list-data="cycleOptions"
                placeholder="请选择通知的周期"
                @change="cycleChange"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="queryData.cycle === 2 || queryData.cycle === 3" :span="showMobilePage ? 24 : 12" >
            <el-form-item :label="cycleDayLabel" prop="cycleDay">
              <selectWithoutHttp
                v-model="queryData.cycleDay"
                :list-data="cycleDayOptions"
                :placeholder="cycleDayPlaceholder"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col v-if="queryData.cycle !== 0" :span="showMobilePage ? 24 : 12" >
            <el-form-item label="通知时间" prop="date">
              <el-time-picker
                v-model="queryData.date"
                size="small"
                value-format="timestamp"
                placeholder="请选择通知时间"
                style="width: 200px;"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="queryData.module.length && !queryData.module.includes(4)">
        <el-row v-for="item in queryData.module" :key="item" class="mb24">
          <el-table
            :data="previewTable(item)"
            :span-method="customSpanMethod"
            border
            style="width: 100%">
            <el-table-column prop="type" label="任务类型" width="80"/>
            <el-table-column prop="name" label="姓名" width="120"/>
            <el-table-column v-if="item === 0 || item === 1" prop="data" label="待处理" />
            <el-table-column v-if="item === 0 || item === 1" prop="data" label="已延期"/>
            <el-table-column v-if="item === 0" prop="data" label="未回收" />
            <el-table-column v-if="item === 0" prop="data" label="延期未回收" />
            <el-table-column v-if="item === 2" prop="data" label="待发布" />
            <el-table-column v-if="item === 2" prop="data" label="待审批" />
            <el-table-column v-if="item === 3" prop="data" label="待提交" />
            <el-table-column v-if="item === 3" prop="data" label="待初审" />
            <el-table-column v-if="item === 3" prop="data" label="待复审" />
            <el-table-column v-if="item === 3" prop="data" label="待确认" />
            <el-table-column v-if="item === 3" prop="data" label="待封存" />
          </el-table>
        </el-row>
      </div>
      <div v-if="queryData.module.length && queryData.module.includes(4)" class="settle-box">
        <p class="settle-title">每月账号结算</p>
        <el-row type="flex" class="response-el-row settle-row">
          <el-col :span="10" >
            <p class="bold-text">发送人</p>
            <p class="second-text">通知任务对象</p>
          </el-col>
          <el-col :span="14" >
            <p class="bold-text">发送时间</p>
            <p class="second-text">--</p>
          </el-col>
          <el-col :span="10" >
            <p class="bold-text">下单日期</p>
            <p class="second-text mb20">--</p>
          </el-col>
          <el-col :span="14" >
            <p class="bold-text">结算金额</p>
            <p class="second-text mb20">--</p>
          </el-col>
        </el-row>
        <p class="settle-btn">点击查看详情</p>
      </div>
    </div>
    <div class="btn-container">
      <el-button :loading="loading" type="primary" size="small" @click="handleOk">确定</el-button>
      <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Title from '@/components/Title';
import { getDepartmentAll, noticeAdd, noticeEdit } from '@/api/config';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import filterCascader from '@/components/Common/filterCascader';
import { format } from '@/filters/date';
import { allDeptlist } from '@/api/select';
import { handelDepartmentData } from '@/utils';
import { mapState } from 'vuex';

export default {
  components: { Title, selectWithoutHttp, filterCascader, selectWithUserLoad },
  data() {
    const validateType = (msg) => {
      return (rule, value, callback) => {
        const type = this.queryData.type;
        let data = null;
        if (type === 0) {
          data = this.queryData.receiveDept;
        } else {
          data = this.queryData.receiveUser;
        }
        if (data && data.length > 0) { callback(); } else { callback(new Error(msg)); }
      };
    };
    return {
      dialogVisible: false,
      kindId: null,
      queryData: {
        module: [],
        type: 0,
        receive: [],
        receiveUser: [],
        receiveDept: [],
        copyReceive: [],
        cycle: '',
        cycleDay: '',
        date: '',
        followUsers: []
      },
      rules: {
        module: [{ required: true, trigger: 'change', message: '请选择通知任务' }],
        type: [{ required: true, trigger: 'change', message: '请选择通知类型' }],
        followUsers: [{ required: true, trigger: 'change', message: '请选择跟进人' }],
        receive: [{ required: true, trigger: 'change', validator: validateType('请选择通知对象') }],
        cycle: [{ required: true, trigger: 'change', message: '请选择通知周期' }],
        cycleDay: [{ required: true, trigger: 'change', message: '请选择通知日期' }],
        date: [{ required: true, trigger: 'change', message: '请选择通知时间' }]
      },
      loading: false,
      taskModulesOptions: [
        { id: 0, value: '合同审批', disabled: false },
        { id: 1, value: '付款申请', disabled: false },
        { id: 2, value: '渠道订单', disabled: false },
        { id: 3, value: '项目订单', disabled: false },
        { id: 4, value: '每月账号结算', disabled: false }
      ],
      deptTreeList: [],
      typeOptions: [
        { id: 0, value: '部门' }
        // { id: 1, value: '个人' } 暂时隐藏
      ],
      cycleOptions: [
        { id: 0, value: '不通知' },
        { id: 1, value: '每天' },
        { id: 2, value: '每周' },
        { id: 3, value: '每月' }
      ],
      isEdit: false,
      allDeptList: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    cycleDayLabel() {
      const cycle = this.queryData.cycle;
      let label = '';
      switch (cycle) {
        case 2: label = '选择星期'; break;
        case 3: label = '选择日期'; break;
      }
      return label;
    },
    cycleDayPlaceholder() {
      const cycle = this.queryData.cycle;
      let label = '请选择';
      switch (cycle) {
        case 2: label = '请选择星期几'; break;
        case 3: label = '请选择每月几号'; break;
      }
      return label;
    },
    cycleDayOptions() {
      const cycle = this.queryData.cycle;
      let options = [];
      if (cycle === 2) {
        options = [
          { id: 1, value: '星期一' }, { id: 2, value: '星期二' },
          { id: 3, value: '星期三' }, { id: 4, value: '星期四' },
          { id: 5, value: '星期五' }, { id: 6, value: '星期六' },
          { id: 7, value: '星期日' }
        ];
      } else if (cycle === 3) {
        for (let i = 1; i <= 31; i++) {
          options.push({ id: i, value: `每月${i}号` });
        }
      }
      return options;
    }
  },
  created() {
    this.queryDeptTreeList();
    this.getAllDeptList();
  },
  methods: {
    previewTable(data) {
      return {
        0: [
          { type: '合同审批', name: '通知对象名称', data: 0 },
          { type: '合同审批', name: '通知对象名称', data: 0 },
          { type: '合同审批', name: '通知对象名称', data: 0 }
        ],
        1: [
          { type: '付款申请', name: '通知对象名称', data: 0 },
          { type: '付款申请', name: '通知对象名称', data: 0 },
          { type: '付款申请', name: '通知对象名称', data: 0 }
        ],
        2: [
          { type: '渠道订单', name: '通知对象名称', data: 0 },
          { type: '渠道订单', name: '通知对象名称', data: 0 },
          { type: '渠道订单', name: '通知对象名称', data: 0 }
        ],
        3: [
          { type: '项目订单', name: '通知对象名称', data: 0 },
          { type: '项目订单', name: '通知对象名称', data: 0 },
          { type: '项目订单', name: '通知对象名称', data: 0 }
        ]
      }[data];
    },
    customSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0 && columnIndex === 0) {
        const _col = row > 0 ? 0 : 1;
        return {
          rowspan: 3,
          colspan: _col
        };
      } else if (rowIndex !== 0 && columnIndex === 0) {
        return {
          rowspan: 0,
          colspan: 0
        };
      }
    },
    openDialog(item = null) {
      this.isEdit = false;
      if (item) {
        this.isEdit = true;
        const data = JSON.parse(JSON.stringify(item));
        // 接收对象根据type不同，选择用户或者部门
        data.type = Number(data.type);
        data.cycle = Number(data.cycle);
        // module 转译
        if (data.module && typeof data.module === 'string') {
          data.module = data.module.split(',').map(i => Number(i));
        }
        // 通知对象
        if (data.receives) {
          if (data.type === 0) {
            data.receiveDept = data.receives.map(i => i.id);
          } else if (data.type === 1) {
            data.receiveUser = data.receives.map(i => {
              return {
                id: i.id, userName: i.name
              };
            });
          }
        }
        // 抄送对象
        if (data.copyReceives) {
          data.copyReceive = data.copyReceives.map(i => {
            return i.id;
          });
        }
        // 把 HH:mm:ss 转成毫秒时间戳
        if (data.date) {
          data.date = this.parseTime(data.date);
        }
        if (data.cycle === 0 || data.cycle === 1) data.cycleDay = 0;

        delete data.receives;
        delete data.receiveName;
        delete data.copyReceives;
        delete data.copyReceiveName;
        delete data.createrName;
        delete data.moduleName;
        this.queryData = data;
        if (data.followUsers && data.followUsers.length > 0) {
          data.followUsers = data.followUsers.map(item => {
            item.userName = item.username;
            return item;
          });
        }
        this.$set(this.queryData, 'followUsers', data.followUsers || []);
        this.handleModule();
        this.kindId = data.id;
      }
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
      this.kindId = null;
      this.queryData = {
        module: [],
        type: 0,
        receive: [],
        receiveUser: [],
        receiveDept: [],
        copyReceive: [],
        cycle: '',
        cycleDay: '',
        date: '',
        followUsers: []
      };
      for (let i = 0; i < 5; i++) {
        this.taskModulesOptions[i].disabled = false;
      }
      this.$refs.configKindForm.resetFields();
    },
    handleOk() {
      this.$refs.configKindForm.validate(vaild => {
        if (vaild) {
          const params = JSON.parse(JSON.stringify(this.queryData));
          if (params.type === 0 && Array.isArray(params.receiveDept)) { // 通知部门
            params.receive = params.receiveDept.join(',');
          } else if (params.type === 1 && Array.isArray(params.receiveUser)) { // 通知个人
            params.receive = params.receiveUser.map(i => i.id).join(',');
          }

          if (params.copyReceive && Array.isArray(params.copyReceive)) params.copyReceive = params.copyReceive.join(',');
          if (params.module && Array.isArray(params.module)) params.module = params.module.join(',');

          if (params.cycle === 2 || params.cycle === 3) {
            params.noticeTime = `${params.cycle}/${params.cycleDay}/${format(params.date, 'HH:mm:ss')}`;
          } else if (params.cycle === 1) {
            params.noticeTime = `${params.cycle}/${format(params.date, 'YYYY-MM-DD')}/${format(params.date, 'HH:mm:ss')}`;
          }
          if (Array.isArray(params.followUsers)) {
            params.followUsers = params.followUsers.map(item => {
              return item.id;
            }).join();
          }
          if (params.module.includes(4)) {
            params.type = '3';
          }
          delete params.cycleDay;
          delete params.date;
          delete params.receiveDept;
          delete params.receiveUser;
          if (this.isEdit) {
            this.toEdit(params);
          } else {
            this.toAdd(params);
          }
        } else {
          return false;
        }
      });
    },
    toAdd(params) {
      this.loading = true;
      noticeAdd(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$emit('update');
          this.$message.success('添加成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        this.dialogVisible = false;
        console.error(err);
      });
    },
    toEdit(params) {
      this.loading = true;
      params.id = this.kindId;
      noticeEdit(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$emit('update');
          this.$message.success('编辑成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        this.dialogVisible = false;
        console.error(err);
      });
    },
    cycleChange() {
      this.queryData.cycleDay = '';
    },
    parseTime(time) {
      // 时分秒转成毫秒的时间戳
      return Date.parse('2021-01-01 ' + time);
    },
    /**
     * 下拉数据
     */
    getAllDeptList() {
      allDeptlist().then(res => {
        handelDepartmentData(res.data, true);
        this.allDeptList = res.data;
      });
    },
    queryDeptTreeList(sort = false) {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    handleModule() {
      if (this.queryData.module.includes(4)) {
        // 选择了每月结算，禁选其他选项
        for (let i = 0; i < 4; i++) {
          this.taskModulesOptions[i].disabled = true;
        }
      } else if (this.queryData.module.length === 0) {
        // 清空选择，放开禁选
        for (let i = 0; i < 5; i++) {
          this.taskModulesOptions[i].disabled = false;
        }
      } else {
        // 选择其他选项，禁选每月结算
        this.taskModulesOptions[4].disabled = true;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.task-box {
  max-height: 70vh;
  overflow-y: auto;
}
.notice-form {
  &::v-deep {
    .el-select__tags{
      margin-top: 0px;
    }
    .el-input__inner {
      width: 200px;
    }
    .el-tag.el-tag--info {
      color: #406eff;
      background: #eff3fb;
      display: flex;
      align-items: center;
      .el-tag__close {
        right: 0;
        margin: 0 0 0 3px;
      }
    }
    .el-col-12:nth-child(2n) {
      display: flex;
      justify-content: flex-end;
    }
  }
}
.mb24 {
  margin-bottom: 24px;
}
.settle-box {
  background: #ffffff;
  border: 0.5px solid #caccd4;
  border-radius: 8px;
  .settle-title {
    height: 40px;
    margin: 0;
    padding-left: 12px;
    font-size: 16px;
    font-weight: normal;
    color: #985a1b;
    line-height: 40px;
    background: linear-gradient(264deg,#ffefde 5%, #fff8f4 50%, #ffefde 96%);
    border-radius: 8px 8px 0px 0px;
  }
  .settle-row {
    margin: 16px 12px;
    border-bottom: 1px solid #ddd;
    p {
      margin: 0;
      color: #333;
    }
    .bold-text {
      margin-bottom: 4px;
      font-size: 14px;
      font-weight: 500;
    }
    .second-text {
      margin-bottom: 24px;
      font-size: 12px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
  }
  .settle-btn {
    padding-left: 12px;
    font-size: 14px;
    font-weight: 500;
    color: #406eff;
  }
}
.btn-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>
